package com.alphacsp.theedge2012.ui.activities;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import com.alphacsp.theedge2012.R;
import com.alphacsp.theedge2012.data.adapters.SpeakersAdapter;
import com.alphacsp.theedge2012.data.database.DataAccessor;
import com.alphacsp.theedge2012.data.entities.Speaker;
import com.alphacsp.theedge2012.data.service.NetworkService;
import com.alphacsp.theedge2012.data.service.NetworkServiceHelper;
import com.alphacsp.theedge2012.data.service.ServiceListener;
import com.alphacsp.theedge2012.ui.components.qucikaction.QuickAction;
import com.alphacsp.theedge2012.ui.components.qucikaction.QuickActionItem;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Gilad
 * Date: 20/10/10
 * Time: 15:03
 */
public class SpeakersActivity extends ListActivity implements ServiceListener {

    private SpeakersAdapter speakersAdapter;
    private DataAccessor dataAccessor;
    private NetworkServiceHelper networkServiceHelper;
    private Object tag;
    private List<Speaker> speakers;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataAccessor = DataAccessor.getSingleton(this);
        networkServiceHelper = new NetworkServiceHelper(this);

        final String query = getIntent().getStringExtra(SearchManager.QUERY);
        if (query != null && query.length() > 0) {
            speakers = dataAccessor.searchSpeakers(query);
            setContentView(R.layout.speakers_activity_bare);
            speakersAdapter = new SpeakersAdapter(this, R.layout.speakers_activity, speakers);
            setListAdapter(speakersAdapter);
            fetchImages();
        } else {
            initSpeakersList();
            final Intent serviceIntent = new Intent(Intent.ACTION_SYNC, null, this, NetworkService.class);
            serviceIntent.putExtra(NetworkService.STATUS_LISTENER, networkServiceHelper);
            serviceIntent.putExtra(NetworkService.REFRESH_ACTION, NetworkService.REFRESH_SPEAKERS);
            startService(serviceIntent);
        }
    }

    private void initSpeakersList() {
        setContentView(R.layout.speakers_activity);
        speakers = dataAccessor.getAllSpeakers();
        speakersAdapter = new SpeakersAdapter(this, R.layout.speakers_activity, speakers);
        setListAdapter(speakersAdapter);
        fetchImages();
    }

    private void fetchImages() {
        for (Speaker speaker : speakers) {
            SpeakerImageFetcher speakerImageFetcher = new SpeakerImageFetcher();
            speakerImageFetcher.execute(speaker);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        dataAccessor.closeDatabase();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        final Speaker speaker = speakersAdapter.getItem(position);
        Intent intent = new Intent(SpeakersActivity.this, SpeakerDetailsActivity.class);
        intent.putExtra("speakerName", speaker.getName());
        intent.putExtra("speakerCompany", speaker.getCompany());
        intent.putExtra("speakerBio", speaker.getBio());
        intent.putExtra("speakerImageUrl", speaker.getImageUrl());
        startActivity(intent);
    }

    @SuppressWarnings({"UnusedDeclaration"})
    public void imageClickListener(View view) {
        final QuickActionItem addToContact = new QuickActionItem();
        tag = view.getTag();
        addToContact.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                final Speaker speaker = speakersAdapter.getItem((Integer) tag);
                Intent intent = new Intent(SpeakersActivity.this, SpeakerDetailsActivity.class);
                intent.putExtra("speakerName", speaker.getName());
                intent.putExtra("speakerCompany", speaker.getCompany());
                intent.putExtra("speakerBio", speaker.getBio());
                intent.putExtra("speakerImageUrl", speaker.getImageUrl());
                startActivity(intent);
            }
        });
        addToContact.setTitle("Show Details");
        addToContact.setIcon(getResources().getDrawable(R.drawable.ic_menu_info_details));
        QuickAction qa = new QuickAction(view);
        qa.addActionItem(addToContact);
        qa.setAnimStyle(QuickAction.ANIM_AUTO);
        qa.show();
    }

    @SuppressWarnings({"UnusedDeclaration"})
    public void onHomeClick(View view) {
        final Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @SuppressWarnings({"UnusedDeclaration"})
    public void onSearchClick(View v) {
        onSearchRequested();
    }

    public void onReceiveResult(int resultCode, Bundle resultData) {
        if (resultCode == NetworkService.STATUS_REFRESHED) {
            initSpeakersList();
        }
    }

    private class SpeakerImageFetcher extends AsyncTask<Speaker, Void, Void> {

        @Override
        protected Void doInBackground(Speaker... speakers) {
            final Speaker speaker = speakers[0];
            final Bitmap bitmap = dataAccessor.fetchImage(speaker.getImageUrl());
            speaker.setSpeakerImage(bitmap);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            speakersAdapter.notifyDataSetChanged();
        }
    }
}

